package com.ruoyi.clf.service.impl;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.ParsedSum;
import org.elasticsearch.search.aggregations.metrics.ParsedValueCount;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderAggregationService {

    @Autowired
    private RestHighLevelClient client;

    public List<Map<String, Object>> getOrderAggregation() throws IOException {
        SearchRequest searchRequest = new SearchRequest("orders");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.size(0);

        // 构建查询条件（修正方法歧义）
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.filter(QueryBuilders.termsQuery("status", (Object) 1, (Object) 2, (Object) 5));
        sourceBuilder.query(boolQuery);

        // 构建聚合
        sourceBuilder.aggregation(
                AggregationBuilders.terms("group_by_merchant")
                        .field("mid")
                        .order(BucketOrder.key(true))
                        .size(10000)
                        .subAggregation(
                                AggregationBuilders.dateHistogram("order_dates")
                                        .field("pay_time")
                                        .calendarInterval(DateHistogramInterval.DAY)
                                        .format("yyyy-MM-dd")
                                        .subAggregation(
                                                AggregationBuilders.terms("group_by_service_type")
                                                        .field("service_type_id")
                                                        .order(BucketOrder.key(true))
                                                        .size(100)
                                                        .subAggregation(AggregationBuilders.sum("revenue_distribution").field("price"))
                                                        .subAggregation(AggregationBuilders.count("order_distribution").field("id"))
                                        )
                        )
        );

        searchRequest.source(sourceBuilder);

        // 执行查询
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);

        // 解析聚合结果（修正类型不匹配）
        List<Map<String, Object>> result = new ArrayList<>();
        ParsedTerms merchantAggs = response.getAggregations().get("group_by_merchant");

        for (Terms.Bucket merchantBucket : merchantAggs.getBuckets()) {
            Map<String, Object> merchantData = new HashMap<>();
            merchantData.put("merchant_id", merchantBucket.getKey());
            merchantData.put("merchant_doc_count", merchantBucket.getDocCount());

            List<Map<String, Object>> dateDataList = new ArrayList<>();
            Histogram dateHistogram = merchantBucket.getAggregations().get("order_dates");

            for (Histogram.Bucket dateBucket : dateHistogram.getBuckets()) {
                Map<String, Object> dateData = new HashMap<>();
                dateData.put("date", dateBucket.getKeyAsString());
                dateData.put("date_doc_count", dateBucket.getDocCount());

                List<Map<String, Object>> serviceDataList = new ArrayList<>();
                ParsedTerms serviceAggs = dateBucket.getAggregations().get("group_by_service_type");

                for (Terms.Bucket serviceBucket : serviceAggs.getBuckets()) {
                    Map<String, Object> serviceData = new HashMap<>();
                    serviceData.put("service_type_id", serviceBucket.getKey());
                    serviceData.put("service_doc_count", serviceBucket.getDocCount());

                    // 获取收入和订单量（修正类型）
                    ParsedSum revenue = serviceBucket.getAggregations().get("revenue_distribution");
                    ParsedValueCount orderDistribution = serviceBucket.getAggregations().get("order_distribution");

                    serviceData.put("revenue", revenue.getValue());
                    serviceData.put("order_count", orderDistribution.getValue());
                    serviceDataList.add(serviceData);
                }

                dateData.put("services", serviceDataList);
                dateDataList.add(dateData);
            }

            merchantData.put("dates", dateDataList);
            result.add(merchantData);
        }

        return result;
    }
}